package com.telnetnz.ticketdesk.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import org.apache.log4j.Logger;

import com.rockbb.common.utilities.security.CaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.telnetnz.ticketdesk.action.base.BasicSessionAction;

public class CaptchaAction extends BasicSessionAction
{
	private static Logger logger = Logger.getLogger(CaptchaAction.class);

	public String doJsInclude()
	{
		DefaultRequestBean bean = new DefaultRequestBean();
		String elementId = bean.get("element");
		String output = "captcha_image(\""+elementId+"\",\""+baseLink("captcha_image")+"\");";
		this.set_raw_string(output);
		return SUCCESS;
	}

	public String doGenerate() 
	{
		try 
		{
			String token = getSession().getSession_token();

			// Generate the image
			BufferedImage challenge = CaptchaService.getImageChallenge(token);

			// Compress it to jpeg
			ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);

			this.set_streambytes("image/jpeg", "attachment", "captcha.jpg", jpegOutputStream.toByteArray());
		} 
		catch (IllegalArgumentException e)
		{
			this.set_streambytes("image/jpeg", "attachment", "captcha.jpg", new byte[]{});
			logger.info("IllegalArgumentException");
			logger.debug("Exception Details", e);
		} 
		catch (Exception e)
		{
			this.set_streambytes("image/jpeg", "attachment", "captcha.jpg", new byte[]{});
			logger.info("UnknownException");
			logger.debug("Exception Details", e);
		}

		return SUCCESS;
	}
}
